import { ArtifactPreviewPanel } from "@renderer/components/business/artifacts/artifact-preview-panel";
import {
  ChatInput,
  type ChatInputRef,
} from "@renderer/components/business/chat-input";
import { MessageList } from "@renderer/components/business/message-list";
import { Button } from "@renderer/components/ui/base/button";
import { useSidebar } from "@renderer/components/ui/base/sidebar";
import { useActiveTab } from "@renderer/hooks/use-active-tab";
import { useArtifact } from "@renderer/hooks/use-artifact";
import { useChat } from "@renderer/hooks/use-chat";
import { useChatInputFocus } from "@renderer/hooks/use-chat-input-focus";
import { cn } from "@renderer/lib/utils";
import { useActiveThreadId, useTabs } from "@renderer/queries";
import {
  useChatSettings,
  useLayoutModeSetting,
} from "@renderer/queries/hooks/use-settings";
import { motion } from "motion/react";
import { useRef } from "react";
import { useTranslation } from "react-i18next";
import { NewThread } from "./new-thread";

export function ChatPage() {
  const { t } = useTranslation();
  const scrollRef = useRef<HTMLDivElement | null>(null);
  const chatInputRef = useRef<ChatInputRef>(null);
  const { isTransitioning } = useSidebar();
  const { data: activeThreadId } = useActiveThreadId();
  const { activeTab } = useActiveTab();
  const { messages, streaming, stopStreamChat, handleScroll } =
    useChat(scrollRef);
  const { isArtifactOpen } = useArtifact();
  const chatSettings = useChatSettings();
  const { data: layoutMode } = useLayoutModeSetting();
  const { data: tabs } = useTabs();
  useChatInputFocus(chatInputRef);

  const isWelcomeState =
    (!activeThreadId && activeTab?.type === "thread") || tabs?.length === 0;

  const getLayoutClass = (mode: string | null | undefined) => {
    switch (mode) {
      case "wide":
        return "max-w-[960px] px-8";
      case "ultra-wide":
        return "max-w-[1440px] px-6";
      default:
        return "max-w-[720px]";
    }
  };

  if (isWelcomeState) {
    return <NewThread />;
  }

  return (
    <div
      className={cn(
        "relative flex h-full w-full",
        isArtifactOpen ? "" : "flex-1",
      )}
    >
      <div
        className={cn(
          "flex h-full flex-col py-6 transition-all duration-300 ease-in-out",
          isArtifactOpen ? "flex-[0_0_60%]" : "flex-1",
        )}
      >
        <div
          ref={scrollRef}
          className="flex-1 space-y-4 overflow-y-auto"
          onScroll={handleScroll}
          style={{
            scrollbarGutter: "stable",
            overflowAnchor: "none", // 禁用浏览器的自动锚定以减少抖动
            overscrollBehavior: "contain", // 阻止滚动链式反弹
          }}
        >
          <MessageList
            messages={messages}
            settings={chatSettings}
            layoutMode={
              (layoutMode ?? "default") as "default" | "wide" | "ultra-wide"
            }
          />
        </div>

        <motion.div
          layoutId={isTransitioning ? undefined : "chat-input"}
          initial={{ opacity: 0 }}
          exit={{ opacity: 0 }}
          animate={{ opacity: 1 }}
          transition={{
            duration: isTransitioning ? 0 : 0.3,
            ease: "easeInOut",
          }}
          className={cn(
            "relative mx-auto w-full pt-4",
            getLayoutClass(layoutMode),
          )}
        >
          <ChatInput ref={chatInputRef} streaming={streaming} />
          <Button
            className={cn(
              "-top-[-5px] -translate-x-1/2 -translate-y-full absolute left-1/2 z-10",
              {
                hidden: !streaming,
              },
            )}
            intent="secondary"
            size="sm"
            onClick={stopStreamChat}
          >
            {t("stop-generating")}
          </Button>
        </motion.div>
      </div>

      <ArtifactPreviewPanel />
    </div>
  );
}
